﻿using Dilon.Application.Entity.TBK;
using Dilon.Application.Service.TBK.Dto;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace Dilon.Application.Service.TBK
{
    /// <summary>
    /// 淘宝客接口
    /// </summary>
    [ApiDescriptionSettings(Name = "TBK", Order = 999)]
    [AllowAnonymous]
    public class TbkServices : ITbkServices, IDynamicApiController, ITransient
    {

        protected   string appkey = "";
        protected   string secret = "";
        protected   string url = "";
        protected ITopClient client;

        private readonly IRepository<Banner> _bannerRep;


        public TbkServices(IConfiguration configuration, IRepository<Banner> bannerRep)
        {
            appkey = configuration["TBK:appkey"];
            secret = configuration["TBK:secret"];
            url = configuration["TBK:openUrl"];
            client = new DefaultTopClient(url, appkey, secret);

            _bannerRep = bannerRep;
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            AppipGetRequest req = new AppipGetRequest();
            AppipGetResponse rsp = client.Execute(req);

            return rsp.Ip;
        }
        /// <summary>
        /// 获取banner
        /// </summary>
        /// <param name="location">位置</param>
        /// <returns></returns>
        public async Task<dynamic>  GetBanner(string location ="top") { 
            var apps = _bannerRep.DetachedEntities.Where(u => u.Location == location); 
            var appList = await apps.Select(u => new BannerOutput
            {
              image=u.ImageUrl,
              title=u.Title,
              url=u.Url 
            }).ToListAsync();  
            return appList;
        }

        /// <summary>
        /// 淘宝客-推广者-官方活动转链 
        /// </summary>
        /// <param name="ActivityId"></param>
        /// <returns></returns>

        public dynamic GetActivityInfo(string  ActivityId) {

            TbkActivityInfoGetRequest req = new TbkActivityInfoGetRequest();
            req.ActivityMaterialId = ActivityId; //"1582769252220";
            req.AdzoneId = 127920968L;
            req.SubPid = "mm_29000257_33130434_127920968";
            //req.RelationId = 123L;
            TbkActivityInfoGetResponse rsp =   client.Execute(req);
            // Console.WriteLine(rsp.Body);
            return rsp.Data;
        }

    }
}
